﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AForge;
using AForge.Robotics.Lego;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Imaging;
using AForge.Imaging.Filters;
using PPP;
using System.Threading;
using AForge.Controls;
using System.Timers;




namespace PPP
{
    public partial class Form1 : Form
    {
        private FilterInfoCollection videoDevices;
        private bool playB = true;
        private Bitmap img = null;
        private Bitmap filteredImg = null;
        delegate void mydel();
        delegate void mydel2();
        private VideoCaptureDevice videoSource;
        private mydel ProcImageDelegate;
        private mydel2 JoystickDelegate;
        private Joystick.Status laststatus;
        private Joystick joystick;
        private float lastx = 0;
        private float lasty = 0;
        private float lastz = 0;

        private System.Timers.Timer time;
        private System.Timers.Timer time2;
        private bool haveJoystick = false;
        private List<Joystick.DeviceInfo> joysticklist;
        private System.Timers.Timer RealClock = new System.Timers.Timer(1000);
        //int jj = 0;
        Communication com = new Communication();
        private bool connected = false;

        private DateTime lastAliveCall = DateTime.Now;

      

        #region ////////////////////////////////////Form Specifics//////////////////////////////////////////////////
        
        public Form1()
        {
            com = new Communication();

            InitializeComponent();



            ///////////////////////////////////////Display Video Devices  //////////////////////////////////////////////////////////      

            ProcImageDelegate = new mydel(ProcImage);
            time2 = new System.Timers.Timer(100);
            time2.Elapsed += new ElapsedEventHandler(time2_Elapsed);

            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            //////////////////////////////////Joystick Devices   //////////////////////////////////////////////////////////////     


            JoystickDelegate = new mydel2(JoystickFunc);


            trackBar1.ValueChanged += new EventHandler(ForwardBackwardValueChange);
            trackBar2.ValueChanged += new EventHandler(UpDownValueChange);
            trackBar3.ValueChanged += new EventHandler(LeftRightValueChange);

            textBox1.Text = "" + 10;
            textBox2.Text = "" + 10;
            textBox3.Text = "" + 10;

            time = new System.Timers.Timer(100);
            time.Elapsed += new ElapsedEventHandler(time_Elapsed);

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            ///////////////////////This will inform the Rich Textbox on bottom of Map to display new info/////////////////////////////////////////////////////////////////////////

            this.mapControl1.InfoChage += new MapControl.FunctionPointer(mapControl1_InfoChage);
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            dataGridView1.DataError += new DataGridViewDataErrorEventHandler(dataGridView1_DataError);
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////       

            RealClock.Elapsed += new ElapsedEventHandler(RealClock_Elapsed);
            RealClock.Start();
            ///////////////////////////////////////////////////////////////////////////////////////////////////////
            com.GotMOData += new Communication.showData(com_GotMOData);
            com.DisplayINOUTDATA += new Communication.showINOUT(com_DisplayINOUTDATA);
            com.GotHBData += new Communication.showData(com_GotHBData);

        }

      

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {


            if (connected == true)
            {

                MessageBox.Show("Please disconnect first before closing");
               ((System.ComponentModel.CancelEventArgs) e).Cancel = true;

            }
            else if (connected == false)
            {

                if (com != null)
                {
                    com.GotMOData -= com_GotMOData;
                    com.StopCommuniation();
                }

                if (time2 != null)
                {
                    time2.Stop();
                    time2.Dispose();
                }


                if (time != null)
                {
                    time.Stop();
                    time.Dispose();
                }

                if (RealClock != null)
                {
                    RealClock.AutoReset = false;
                    RealClock.Stop();
                    RealClock.Dispose();
                }


                if (videoSource != null)
                {
                    videoSource.SignalToStop();

                }

                this.Dispose();
            }
        }
        
        void RealClock_Elapsed(object sender, ElapsedEventArgs e)
        {


            try
            {
                this.Invoke((MethodInvoker)delegate {


                    DateTime dt = DateTime.Now;

                    labelClock.Text = "Current Time: " + dt;

                    //TimeSpan pSpan = DateTime.Now - lastAliveCall;


                    //if (((int)pSpan.TotalMilliseconds >= 1000) && (com.UAVisAlive == false))
                    //{
                        
                    //    UAValiveIndicator.BackColor =Color.Red;

                    ////    MessageBox.Show("HI");
                      
                    //    lastAliveCall = DateTime.Now;

                    //}
                
                                
                
                
                
                });

            }
            catch (Exception ex)
            {

            }


        }
        
        private void Form1_Load(object sender, EventArgs e)
        {

            //   string str = "hi \r$MO$ ff\rhi\rjjhi $MO,54,78,56\r";



            //   string[] splittedString = str.Split('$');//splits the sentence where it sees $


            //   List<int> ind= new List<int>();

            //   for (int i = 0; i < splittedString.Length; i++)
            //   {

            //       if (splittedString[i].Contains("\r")) 
            //       {

            //           ind.Add(i); 

            //       }


            //   }

            //List<string> indd= new List<string>();


            //   foreach (int item in ind)
            //   {

            //     indd.Add( splittedString[item]);

            //   }


            //   string[] arry = indd.ToArray();



            //   MessageBox.Show("" + arry.Length);








        }
        
        #endregion

        

        #region ////////////////////////////Flying Instruments///////////////////////////////////////
        void attitudeIndicatorInstrumentControl1_NewAttitude(double aircraftPitchAngle, double aircraftRollAngle)
        {
           

        }

        void headingIndicatorInstrumentControl1_NewHeading(int Heading)
        {

          

        }

        void verticalSpeedIndicatorInstrumentControl1_NewVerticalSpeed(int verticalSpeed)
        {

        

        }

        void altimeterInstrumentControl1_NewAltitude(int Altitude)
        {
        
        }

        void airSpeedIndicatorInstrumentControl1_NewSpeed(int speed)
        {
           
        }
                                         
        #endregion
       
         
        
        #region////////////////////////////////////////// This is Video Section ////////////////////////////////////////

        void time2_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
               

                this.Invoke(ProcImageDelegate);
            }
            catch (Exception ex )
            {
                
               
            }
        }

        private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            
            img = (Bitmap)eventArgs.Frame.Clone();
                               
            //  this.Invoke(del);
                   

        }        

        private void TrackBar3_ValueChanged(object sender, EventArgs e)
        {               

        }

        private void buttonDefault_Click(object sender, EventArgs e)
        {          

            TrackBarBrightness3.Value = 0;
            TrackBarContrast3.Value = 20;
            TrackBarSaturation3.Value = 20;
            TrackBarHue3.Value = 0;
            TrackBarGamma3.Value = 20;           
        }
        
        private void ProcImage()
        {
            if (img != null)
            {
                    DateTime pDateTimeStart = DateTime.Now;
                    QColorMatrix pQColorMatrix = new QColorMatrix();
                    pQColorMatrix.ScaleColors(TrackBarContrast3.Value * 0.05f, QColorMatrix.MatrixOrder.MatrixOrderPrepend);
                    pQColorMatrix.TranslateColors(TrackBarBrightness3.Value * 0.05f, QColorMatrix.MatrixOrder.MatrixOrderAppend);
                    pQColorMatrix.SetSaturation(TrackBarSaturation3.Value * 0.05f, QColorMatrix.MatrixOrder.MatrixOrderAppend);
                    pQColorMatrix.RotateHue(TrackBarHue3.Value * 4.0f);
                    filteredImg =  pQColorMatrix.Adjust(img, TrackBarGamma3.Value * 0.05f);

             //   pictureBox1.Image = filteredImg;

                screen1.Image = filteredImg;

                    TimeSpan pSpan = DateTime.Now - pDateTimeStart;
                    textBoxTime3.Text = ((int)pSpan.TotalMilliseconds).ToString();






                //Thread.Sleep(100);






               // System.Console.WriteLine("hey");
            }
        }

        private void Capture_Click(object sender, EventArgs e)
        {
            try
            {
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

                if (videoDevices.Count == 0)
                    throw new ApplicationException();

                camerasCombo.Items.Clear();

                foreach (FilterInfo device in videoDevices)
                {
                    camerasCombo.Items.Add(device.Name);
                }

                camerasCombo.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                camerasCombo.Items.Clear();
                camerasCombo.Items.Add("No local capture devices");
                videoDevices = null;

             Logger.AppendText("Error with " + ex.TargetSite + "   Message: " + ex.Message + "\n\r");
            }


          



            try
            {
                if (playB == true)
                {

                    // connect to camera
                    videoSource = new VideoCaptureDevice(videoDevices[camerasCombo.SelectedIndex].MonikerString);
                    videoSource.DesiredFrameSize = new Size(320, 240);
                    videoSource.DesiredFrameRate = 50;

                    // videoSourcePlayer.VideoSource = videoSource;
                    videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
                    videoSource.Start();
                    time2.Start();

                    playB = false;
                    Capture.Text = "No Capture";

                }
                else if (playB == false)
                {
                    camerasCombo.Items.Clear();
                    time2.Stop();
                    videoSource.SignalToStop();

                    Capture.Text = "Capture";
                    playB = true;

                }
            }
            catch (Exception ex)
            {
                
                 Logger.AppendText("Error with " + ex.TargetSite + "   Message: " + ex.Message + "\n\r");
            }
        }

        #endregion



        #region /////////////////////////////////////////Joystick Controls//////////////////////////////////////////////////////////

        private void timer1_Tick(object sender, EventArgs e)
        {
          this.Invoke(JoystickDelegate);
        }


        void time_Elapsed(object sender, ElapsedEventArgs e)
        {

            try
            {
                this.Invoke(JoystickDelegate);
            }
            catch (Exception)
            {
                
               
            }
        }

        //Track bars
        private void ForwardBackwardValueChange(object sender, EventArgs e)
        {
            textBox1.Text =""+ ((TrackBar)sender).Value;




            if (EnableJoysticButton.Text.Contains("Enable Joystick"))
            {

                //To do Send Data from here




           }
         

        }
       
        private void UpDownValueChange(object sender, EventArgs e)
        {
            textBox2.Text = "" + ((TrackBar)sender).Value;

            if (EnableJoysticButton.Text.Contains("Enable Joystick"))
            {
                //To do Send Data from here
            }
        }
       
        private void LeftRightValueChange(object sender, EventArgs e)
        {
            textBox3.Text = "" + ((TrackBar)sender).Value;


            if (EnableJoysticButton.Text.Contains("Enable Joystick"))
            {

                //To do Send Data from here

            }

        }
                
        //Buttons             
        private void button5_Click(object sender, EventArgs e)
        {
            if (EnableJoysticButton.Text.Contains("Enable Joystick"))
            {
            EnableJoysticButton.Text = "Disable Joystick";            
            haveJoystick = false;
            joysticklist = null;
            joystick = null;
            time.Start();
            }
         else if (EnableJoysticButton.Text.Contains("Disable Joystick")){

           time.Enabled = false;                   
           EnableJoysticButton.Text = "Enable Joystick";          
           haveJoystick = false;
           joysticklist = null;
           joystick = null;
           textBox4.Text = " ";
         



            } 
        }
        
        private void JoystickFunc()
        {                
          //  jj++ ; //for Debogging to see if is calling this funckion everytime
          //Logger.AppendText("Iterations: "+jj +"\n\r");

           
            joysticklist = Joystick.GetAvailableDevices();

         
            try
            {             

                if (joysticklist.Count == 0 || joysticklist == null)
                    throw new Exception("There is no Joystick Connected to PC");


                if (haveJoystick == false)
                {                   
                    textBox4.Text = joysticklist.Count.ToString();   
                   
                    joystick = new Joystick(0); 
                    haveJoystick = true;
                }  
                
                
                // get its current status
                    Joystick.Status status = joystick.GetCurrentStatus();
                    // check if 1st button is pressed



////////////////////////////  Buttons  ///////////////////////////////////////////////////////////////////

                    if (status.IsButtonPressed(Joystick.Buttons.Button1))
                    {
                        //Do Something 



                        button1.BackColor = Color.Green;

                    }
                    else
                    {

                        button1.BackColor = Color.DarkGray;

                    }

                    if (status.IsButtonPressed(Joystick.Buttons.Button2))
                    {
                        //Do Something 



                        button2.BackColor = Color.Green;

                    }
                    else
                    {

                        button2.BackColor = Color.DarkGray;

                    }

                    if (status.IsButtonPressed(Joystick.Buttons.Button3))
                    {
                        //Do Something 

                     

                        button3.BackColor = Color.Green;

                    }
                    else
                    {

                        button3.BackColor = Color.DarkGray;

                    }

                    if (status.IsButtonPressed(Joystick.Buttons.Button4))
                    {
                        //Do Something 


                        button4.BackColor = Color.Green;
                     

                    }
                    else
                    {

                        button4.BackColor = Color.DarkGray;

                    }


                    //////Axis

                    if (Math.Abs(status.YAxis - lasty) >= .1)
                    {

                        



                    lasty = status.YAxis;
                    trackBar1.Value = (((int)(lasty * 10)) * -1) + 10;

                    }

                    if (Math.Abs(status.RAxis - lastz) >= .1)
                    {
                        lastz = status.RAxis;
                        trackBar2.Value = (((int)(lastz * 10))*-1 )+ 10;
                
                    }                                      
                    
                    if (Math.Abs(status.XAxis - lastx) >= .1)
                    {
                        lastx = status.XAxis;
                        trackBar3.Value = ((int)(lastx * 10))+10;

                    }                   
    


            }
            catch (Exception ex)
            { 
            time.Enabled=false;     
            textBox4.Text = " ";
            EnableJoysticButton.Text = "Enable Joystick";
            Logger.AppendText("Error with " + ex.TargetSite + "   Message: " + ex.Message + "\n\r");
            haveJoystick = false;
            joysticklist = null;
            joystick = null;             
                 
                
            }
           
        }
            
        #endregion
        

        #region //////////////////////////////////////////Map functions////////////////////////////////

        void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Please enter a numerical value in Meters");
        }

        void mapControl1_InfoChage(List<FlyingCommands> listComands)
        {
            richTextBox1.Clear();

          
            

            if (listComands != null && this.mapControl1.Contains(this.mapControl1.uav))
            {

                
                  dataGridView1.DataSource = listComands;

                  dataGridView1.Columns[0].ReadOnly = true;
                  dataGridView1.Columns[1].ReadOnly = true;
                  dataGridView1.Columns[2].ReadOnly = true;           

 richTextBox1.AppendText( String.Format(" UAV  x : {0:0.##} ", this.mapControl1.uav.WaypointX)+  String.Format(" y : {0:0.##} ", this.mapControl1.uav.WaypointY)+ String.Format(" Alt : {0:0.##} ", this.mapControl1.uav.WaypointZ)+ String.Format(" Angle : {0:0.##} ", this.mapControl1.uav.WaypointT)+ "\r\n");



                foreach (FlyingCommands var in listComands)
                {

                    richTextBox1.AppendText(String.Format(" Waypoint : {0:0.##}", listComands.IndexOf(var)) + String.Format(" Distance : {0:0.##}", var.Distance) + String.Format(" Direction : {0:0.##}", var.Angle) + String.Format(" Altitude : {0:0.##}", var.Altitude) + "\r\n");
                    
                }
            }
            else
            {

              //  MessageBox.Show("null");

            }





        }
        
        private void addWaypointsB_Click(object sender, EventArgs e)
        {

            this.mapControl1.AddWaypoint = true;
            this.mapControl1.RemoveWaypoint = false;

            addWaypointsB.Enabled = false;
            RemoveWaypointsB.Enabled = true;
            MoveWaypointsB.Enabled = true;     

        }

        private void RemoveWaypointsB_Click(object sender, EventArgs e)
        {
            this.mapControl1.RemoveWaypoint = true;
            this.mapControl1.AddWaypoint = false;



            RemoveWaypointsB.Enabled = false;
            addWaypointsB.Enabled = true;
            MoveWaypointsB.Enabled = true;     


        }

        private void MoveWaypointsB_Click(object sender, EventArgs e)
        {

            this.mapControl1.RemoveWaypoint = false;
            this.mapControl1.AddWaypoint = false;


            MoveWaypointsB.Enabled = false;
            RemoveWaypointsB.Enabled = true;
            addWaypointsB.Enabled = true; 


        }

        private void Clear_Click(object sender, EventArgs e)
        {
            this.mapControl1.clearMap();

        }
                              
        private void MapRealWHB_Click(object sender, EventArgs e)
        {
            if (MapRealWHB.Text.Contains("Set"))
            {
                try
                {
                    if (textBox5.Text != "")
                    {
                        this.mapControl1.RealMapWidth = int.Parse(textBox5.Text);
                        this.mapControl1.RealMapHeight = int.Parse(textBox5.Text);

                        this.mapControl1.UpdatePixelToMeters();

                        textBox5.Enabled = false;
                        MapRealWHB.Text = "Edit";
                    }
                }
                catch (Exception ex)
                {

                    MessageBox.Show("Please enter a numerical value in Meters");
                }


            }
            else if (MapRealWHB.Text.Contains("Edit"))
            {

                textBox5.Enabled = true;
                MapRealWHB.Text = "Set";
            }







        }
       
        private void button6_Click(object sender, EventArgs e)
        {

            this.mapControl1.SetUAVDefaultLocOnMap();

        }

        private void ChangeWaypointStettingB_Click(object sender, EventArgs e)
        {

            try
            {
                if (Xm.Text != "" && Ym.Text != "" && Zm.Text != "")
                {
                   
                    this.mapControl1.addWaypointF(float.Parse(Xm.Text),float.Parse(Ym.Text), float.Parse(Zm.Text));
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("Please enter a numerical value in Meters");
            }


        }
                           
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {




            try
            {

                float.Parse(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
            
            }
            catch (Exception ex)
            {
                
               MessageBox.Show("Please enter a numerical value in Meters");
                
            }





                if (this.mapControl1.ListComands != null && this.mapControl1.Contains(this.mapControl1.uav) && e.ColumnIndex == 3)
                {

                    this.mapControl1.ListWaypoits.ElementAt(e.RowIndex).WaypointZ = float.Parse(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());

                    this.mapControl1.ImoveInsideMap();
                    this.mapControl1.Refresh();
                    MessageBox.Show(" index row : " + e.RowIndex + " index Col : " + e.ColumnIndex);
                }

            



            
        }

        private void button7_Click(object sender, EventArgs e)
        {
            try
            {
                if (UAVx.Text != "" && UAVy.Text != "" && UAVz.Text != "" && UAVt.Text != "")
                {
                  this.mapControl1.UpdateUAVonMap(float.Parse(UAVx.Text), float.Parse(UAVy.Text), float.Parse(UAVz.Text), float.Parse(UAVt.Text),0);


                }
            }
            catch (Exception ex)
            {
                
                 MessageBox.Show("Please enter a numerical value in Meters");
            }
        }
        /// <summary>
        /// To be used for communication
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>


        private void UpdateUAVPos(float somethingAndMore)
        {

          //  this.mapControl1.UpdateUAVonMap(float.Parse(UAVx.Text), float.Parse(UAVy.Text), float.Parse(UAVz.Text), float.Parse(UAVt.Text), 1);

        }
        

 private void SendWaypoints_Click(object sender, EventArgs e)
        {
            List < FlyingCommands >  listComands = this.mapControl1.GetComandsToSend();
                    

           if (listComands != null && this.mapControl1.Contains(this.mapControl1.uav))
            {
                string ComList="";
                string WaypointListToSend = "$WL,"+listComands.Count;


                foreach (FlyingCommands var in listComands)
                {

                    ComList += " Waypoint : "+ listComands.IndexOf(var) + " Distance : "+ var.Distance + " Direction : "+ var.Angle + " Altitude : "+ var.Altitude + "\r\n";

                    WaypointListToSend += "," + listComands.IndexOf(var) + "," + var.Altitude + "," + var.Angle + "," + var.Distance;
                    
                  }

              //  WaypointListToSend += "\r";




                if (MessageBox.Show("You are about to send a waypoint list \r\n " + ComList, "Comunication", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    MessageBox.Show("Sending...");

                    MessageBox.Show(WaypointListToSend);

                    ///Send code

                   // serialPort1.wr

                    com.SendDataToUAV(WaypointListToSend);

                    
                }
                else 
                {

                    MessageBox.Show("Aborted");
                }



            }
            else
            {

                MessageBox.Show("No Waypoints");

            }
            

          //  MessageBox.Show("at 0: " + listComands.ElementAt(0).Distance);




        }



 #endregion

        

        #region/////////////////////////////Extras////////////////////////////////////////
        
 private void button8_Click(object sender, EventArgs e)
 {
    screen1.RollAngle += 5;

     screen1.Airspeed +=0;
     screen1.Altitude += 1;
     screen1.Refresh();
 }

 private void button9_Click(object sender, EventArgs e)
 {
     screen1.AngleOfAttack += 5;

     screen1.Refresh();

     //screen1.PitchAngle += 1;



 }

 private void button10_Click(object sender, EventArgs e)
 {
     screen1.Airspeed -= 1;
     screen1.Altitude -= 1; screen1.Refresh();
 }



 private void trackBar4_Scroll(object sender, EventArgs e)
 {
     screen1.PitchAngle = trackBar4.Value;
     screen1.Refresh();
     textBox6.Text =""+ trackBar4.Value;
 }

 private void trackBar5_Scroll(object sender, EventArgs e)
 {
     screen1.AngleOfAttack = (float)trackBar5.Value; screen1.Refresh();
     textBox7.Text =""+ trackBar5.Value;
 }



 private void button14_Click_1(object sender, EventArgs e)
 {
 if (screen1.EnableHUD == true)
     {
         screen1.EnableHUD = false;
     }
     else
     {

         screen1.EnableHUD = true;
     }
     screen1.Refresh();
 }

 private void button13_Click_1(object sender, EventArgs e)
 {
  //Speed takes Positive numbers only
     //Altitude takes Positive numbers only
     //Vertical Speed takes Negative and Positive
     //Pitch Angle takes numbers from -90 (down) to +90 (up) degrees
     //Roll Angle takes numbers from -180 (left) to +180 (right) degrees
    
     
     screen1.SetVariables(0,0, 0, 0, -45);
screen1.SetHudColor();

     screen1.Refresh();


 }

 private void trackBar6_Scroll(object sender, EventArgs e)
 {

     screen1.Heading1 = trackBar6.Value;

     screen1.Refresh();

 }

 #endregion



        #region/////////////////////////////Communication and Data distribution/////////////////////////////////////////

 void com_GotHBData(string[] s)
 {
     this.Invoke((MethodInvoker)delegate
     {




         if (s[1].Contains("A"))
         {

             UAValiveIndicator.BackColor = Color.Green;
         }



     });
 }

 private void button11_Click(object sender, EventArgs e)
 {


     if (connected == false)
     {
         try
         {
             if (ComPortTextBox.Text == "" && BaudRateTextBox.Text == "")
             {

                 string s1 = ComPortComboBox.GetItemText(ComPortComboBox.SelectedItem);
                 string s2 = BoudRateComboBox.GetItemText(BoudRateComboBox.SelectedItem);


                     com.MyportName(s1);
                     com.MyBoudRate(int.Parse(s2));


                 }
                 else
                 {


                      com.MyportName("COM" + int.Parse(ComPortTextBox.Text));
                      com.MyBoudRate(int.Parse(BaudRateTextBox.Text));




                 }



                 com.StartCommuniation();
                 // int.
                 connected = true;

                 button11.Text = "Disconnect";
           


         }
         catch (FormatException ex)
         {

             com.StopCommuniation();


             MessageBox.Show("Please provide correct Values for Port Number and Baud Rate Format Incorrect");
         }
         catch (System.IO.IOException ex)
         {


             com.StopCommuniation();


             MessageBox.Show("Problem Conecting error 2");


         }
         catch (Exception ex)
         {


             com.StopCommuniation();


             MessageBox.Show("Problem: " + ex.Message);


         }

     }
     else if (connected == true)
     {
         com.StopCommuniation();

         connected = false;

         button11.Text = "Connect";
         UAValiveIndicator.BackColor = Color.Red;
     }




 }

 void com_GotMOData(string[] s)
 {
     try
     {
         // this.BeginInvoke((MethodInvoker)delegate { richTextBox2.AppendText("Motor 1: " + s[1] + " Motor 2: " + s[2] + " Motor 3: " + s[3] + "\r\n"); });
         this.Invoke((MethodInvoker)delegate { mapControl1.UpdateUAVonMap(int.Parse(s[1]), 40, 1, int.Parse(s[1]), 3); });
         // this.Invoke((MethodInvoker)delegate { screen1.MotorR = int.Parse(s[2]); });
         //this.Invoke((MethodInvoker)delegate { screen1.MotorL = int.Parse(s[3]); });

         //  this.Invoke((MethodInvoker)delegate { mapControl1.Refresh(); });

     }
     catch (Exception ex)
     {

         MessageBox.Show(ex.Message);
     }

  

 }

 void com_DisplayINOUTDATA(string s)
 {
   this.Invoke((MethodInvoker)delegate { richTextBox2.AppendText(s+"\r"); });

   //  this.Invoke((MethodInvoker)delegate { richTextBox2.Text=s + "\r"; });
 
 }

 #endregion

 private void sendCodebutton_Click(object sender, EventArgs e)
 {


     com.SendDataToUAV(sendCodetextBox.Text);

 }

 private void button12_Click(object sender, EventArgs e)
 {
     richTextBox2.Clear();
 }



 























    }

}